package org.black.phoneUtility.database.sqlite;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteTransactionListener;

public class PhoneUtilityTransaction {
	private final boolean batch;
	private List<SQLiteDatabase> databases;
	private Map<String, SQLiteDatabase> databaseTagMap;

	public PhoneUtilityTransaction(boolean batch) {
		this.batch = batch;
		this.databases = new ArrayList<SQLiteDatabase>();
		this.databaseTagMap = new HashMap<String, SQLiteDatabase>();
	}

	public boolean isBatch() {
		return batch;
	}

	public void startTransactionForDb(SQLiteDatabase db, String tag,
			SQLiteTransactionListener listener) {
		if (!hasDbInTransaction(tag)) {
			databases.add(db);
			databaseTagMap.put(tag, db);

			if (listener != null) {
				db.beginTransactionWithListener(listener);
			} else {
				db.beginTransaction();
			}
		}
	}

	public boolean hasDbInTransaction(String tag) {
		return databaseTagMap.containsKey(tag);
	}

	public SQLiteDatabase getDbForTag(String tag) {
		return databaseTagMap.get(tag);
	}

	public void markSuccessful(boolean callerIsBatch) {

		if (!batch || callerIsBatch) {
			for (SQLiteDatabase db : databases) {
				db.setTransactionSuccessful();
			}
		}
	}

	public void finish(boolean callerIsBatch) {
		if (!batch || callerIsBatch) {
			for (SQLiteDatabase db : this.databases) {
				db.endTransaction();
			}
			databases.clear();
			databaseTagMap.clear();
		}
	}
}
